/************************************************************
 *  * EaseMob CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of EaseMob Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from EaseMob Technologies.
 */

#import "ChatListViewController.h"
#import "SRRefreshView.h"
#import "ChatListCell.h"
#import "EMSearchBar.h"
#import "NSDate+Category.h"
#import "RealtimeSearchUtil.h"
#import "ChatViewController.h"
#import "EMSearchDisplayController.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "TongXunLu.h"
#import "UIImageView+EMWebCache.h"
#import "TongXunLuViewController.h"
#import "GroupListViewController.h"
#import "AddFamilyViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "UIColor+Addition.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface ChatListViewController ()<UITableViewDelegate,UITableViewDataSource,SRRefreshDelegate, IChatManagerDelegate,ChatViewControllerDelegate>

@property (strong, nonatomic) NSMutableArray        *dataSource;
@property (strong, nonatomic) NSMutableDictionary  *nameDic;
@property (strong, nonatomic) UITableView           *tableView;
@property (nonatomic, strong) EMSearchBar           *searchBar;
@property (nonatomic, strong) SRRefreshView         *slimeView;
@property (nonatomic, strong) UIView                *networkStateView,*tableHeaderView;

@property (strong, nonatomic) EMSearchDisplayController *searchController;

@property (strong, nonatomic) NSMutableDictionary  *huanXinDic;
@end

@implementation ChatListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataSource = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title=@"村友";
    
    [self getAllHuanXinUserInfo];//获取环信用户
    
    //[[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    //[self removeEmptyConversationsFromDB];
    
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.slimeView];
    self.tableView.tableHeaderView=[self tableHeaderView];
    
    [self createNavBtn];
    [self getTongXunLuInfo];
    [self getMyGroupInfo];
}

-(void)createNavBtn{
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 44)];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [rightBtn setTitle:@"亲人邀请" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor convertHexColorToUIColor:0xffffff] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(addFamily) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 10;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightItem, nil]];
    //[self.navigationItem setRightBarButtonItem:rightItem];
}

#pragma mark - 设置表头本村通讯录和群组

- (UIView *)tableHeaderView
{
    if (_tableHeaderView == nil) {
        
        _tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 114)];
        _tableHeaderView.backgroundColor=[UIColor whiteColor];
        
        UIView *sepraView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15)];
        sepraView.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
        [_tableHeaderView addSubview:sepraView];
        
        float gapWidth=(SCREEN_WIDTH-80)/4.0;
        UIImageView *addressBookImageView=[[UIImageView alloc]init];
        addressBookImageView.frame=CGRectMake(gapWidth, 30, 40, 40);
        addressBookImageView.image=[UIImage imageNamed:@"addressbookimg.png"];
        addressBookImageView.userInteractionEnabled=YES;
        UITapGestureRecognizer *addressBookTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToTongXunLu)];
        [addressBookImageView addGestureRecognizer:addressBookTap];
        [_tableHeaderView addSubview:addressBookImageView];
        
        UILabel *addressBookLabel=[[UILabel alloc]initWithFrame:CGRectMake(gapWidth-5, 73, 50, 18)];
        addressBookLabel.text=@"通讯录";
        addressBookLabel.textAlignment=1;
        addressBookLabel.textColor=[UIColor convertHexColorToUIColor:0x747474];
        addressBookLabel.font=[UIFont systemFontOfSize:14];
        [_tableHeaderView addSubview:addressBookLabel];
        
        UIView *sepraView1=[[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0, 30, 0.5, 62)];
        sepraView1.backgroundColor=[UIColor convertHexColorToUIColor:0xdcdddd];
        [_tableHeaderView addSubview:sepraView1];
        
        UIImageView *groupImageView=[[UIImageView alloc]init];
        groupImageView.frame=CGRectMake(SCREEN_WIDTH-gapWidth-40, 30, 40, 40);
        groupImageView.image=[UIImage imageNamed:@"groupimg.png"];
        groupImageView.userInteractionEnabled=YES;
        UITapGestureRecognizer *groupTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToGroupList)];
        [groupImageView addGestureRecognizer:groupTap];
        [_tableHeaderView addSubview:groupImageView];
        
        UILabel *groupLabel=[[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-gapWidth-40, 73, 40, 18)];
        groupLabel.text=@"群";
        groupLabel.textAlignment=1;
        groupLabel.textColor=[UIColor convertHexColorToUIColor:0x747474];
        groupLabel.font=[UIFont systemFontOfSize:14];
        [_tableHeaderView addSubview:groupLabel];
        
        UIView *sepraView2=[[UIView alloc]initWithFrame:CGRectMake(0, 99, SCREEN_WIDTH, 15)];
        sepraView2.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
        [_tableHeaderView addSubview:sepraView2];
    }
    return _tableHeaderView;
}

-(void)goToTongXunLu{
    
    TongXunLuViewController *tongXunLuVC=[[TongXunLuViewController alloc]init];
    tongXunLuVC.orRefresh=YES;
    tongXunLuVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:tongXunLuVC animated:YES];
}

-(void)goToGroupList{
    
    GroupListViewController *groupVC=[[GroupListViewController alloc]initWithStyle:UITableViewStylePlain];
    groupVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:groupVC animated:YES];
}

-(void)addFamily{
    
    AddFamilyViewController *familyVC=[[AddFamilyViewController alloc]init];
    familyVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:familyVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self refreshDataSource];
    [self registerNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregisterNotifications];
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
    
    for (EMConversation *conversation in conversations) {
        //是群组聊天
        if (conversation.conversationType == eConversationTypeGroupChat) {
            
            BOOL isExist=NO;
            
            for (EMGroup *group in groupArray) {
                
                if ([group.groupId isEqualToString:conversation.chatter]) {
                    
                    isExist=YES;
                    break;
                }
            }
            
            if (!isExist) {
                if (!needRemoveConversations) {
                    needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
                }
                [needRemoveConversations addObject:conversation.chatter];
            }
            
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:YES];
    }
    [self refreshDataSource];
}

- (void)removeChatroomConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (conversation.conversationType == eConversationTypeChatRoom) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:NO];
    }
}

#pragma mark - getter

- (SRRefreshView *)slimeView
{
    if (!_slimeView) {
        _slimeView = [[SRRefreshView alloc] init];
        _slimeView.delegate = self;
        _slimeView.upInset = 0;
        _slimeView.slimeMissWhenGoingBack = YES;
        _slimeView.slime.bodyColor = [UIColor grayColor];
        _slimeView.slime.skinColor = [UIColor grayColor];
        _slimeView.slime.lineWith = 1;
        _slimeView.slime.shadowBlur = 4;
        _slimeView.slime.shadowColor = [UIColor grayColor];
        _slimeView.backgroundColor = [UIColor whiteColor];
    }
    
    return _slimeView;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height ) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ChatListCell class] forCellReuseIdentifier:@"chatListCell"];
    }
    
    return _tableView;
}

- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

#pragma mark - private

- (NSMutableArray *)loadDataSource
{
    NSMutableArray *ret = nil;
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    
    for (EMConversation *conversation in conversations) {
        NSLog(@"%@",conversation.chatter);
    }
    NSArray* sorte = [conversations sortedArrayUsingComparator:
                      ^(EMConversation *obj1, EMConversation* obj2){
                          EMMessage *message1 = [obj1 latestMessage];
                          EMMessage *message2 = [obj2 latestMessage];
                          if(message1.timestamp > message2.timestamp) {
                              return(NSComparisonResult)NSOrderedAscending;
                          }else {
                              return(NSComparisonResult)NSOrderedDescending;
                          }
                      }];
    
    ret = [[NSMutableArray alloc] initWithArray:sorte];
    return ret;
}

// 得到最后消息时间
-(NSString *)lastMessageTimeByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];;
    if (lastMessage) {
        ret = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    
    return ret;
}

// 得到未读消息条数
- (NSInteger)unreadMessageCountByConversation:(EMConversation *)conversation
{
    NSInteger ret = 0;
    ret = conversation.unreadMessagesCount;
    
    return  ret;
}

// 得到最后消息文字或者类型
-(NSString *)subTitleMessageByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];
    if (lastMessage) {
        id<IEMMessageBody> messageBody = lastMessage.messageBodies.lastObject;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Image:{
                ret = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case eMessageBodyType_Text:{
                // 表情映射。
                NSString *didReceiveText = [ConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                ret = didReceiveText;
            } break;
            case eMessageBodyType_Voice:{
                ret = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case eMessageBodyType_Location: {
                ret = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case eMessageBodyType_Video: {
                ret = NSLocalizedString(@"message.vidio1", @"[vidio]");
            } break;
            default: {
            } break;
        }
    }
    
    return ret;
}

#pragma mark - TableViewDelegate & TableViewDatasource

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"chatListCell";
    ChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if (!cell) {
        cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
    }
    EMConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    
    if (conversation.conversationType == eConversationTypeChat) {
        
        cell.name=[_huanXinDic objectForKey:[NSString stringWithFormat:@"%@name",conversation.chatter]];
        cell.placeholderImage = [UIImage imageNamed:@"default_touxiang.png"];
        cell.imageURL=[NSURL URLWithString:[_huanXinDic objectForKey:[NSString stringWithFormat:@"%@pic",conversation.chatter]]];
    }
    else{
        
        NSString *imageName = @"groupchatimg";
        NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
        for (EMGroup *group in groupArray) {
            
            if ([group.groupId isEqualToString:conversation.chatter]) {
                cell.name = group.groupSubject;
                
                imageName = group.isPublic ? @"groupchatimg" : @"groupchatimg";
                break;
            }
        }
        cell.placeholderImage = [UIImage imageNamed:imageName];
        cell.imageURL=nil;
    }
    
    cell.detailMsg = [self subTitleMessageByConversation:conversation];
    cell.time = [self lastMessageTimeByConversation:conversation];
    cell.unreadCount = [self unreadMessageCountByConversation:conversation];
    //if (indexPath.row % 2 == 1) {
    //    cell.contentView.backgroundColor = RGBACOLOR(246, 246, 246, 1);
    //}else{
    cell.contentView.backgroundColor = [UIColor whiteColor];
    //}
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [ChatListCell tableView:tableView heightForRowAtIndexPath:indexPath];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    EMConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    
    ChatViewController *chatController;
    NSString *title = conversation.chatter;
    if (conversation.conversationType != eConversationTypeChat) {
        if ([[conversation.ext objectForKey:@"groupSubject"] length])
        {
            title = [conversation.ext objectForKey:@"groupSubject"];
        }
        else
        {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.chatter]) {
                    title = group.groupSubject;
                    break;
                }
            }
        }
    }else{
        title = [_huanXinDic objectForKey:[NSString stringWithFormat:@"%@name",conversation.chatter]];
    }
    
    NSString *chatter = conversation.chatter;
    chatController = [[ChatViewController alloc] initWithChatter:chatter conversationType:conversation.conversationType];
    chatController.delelgate = self;
    chatController.title = title;
    chatController.chatPicUrl = [_huanXinDic objectForKey:[NSString stringWithFormat:@"%@pic",conversation.chatter]];
    chatController.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:chatController animated:YES];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EMConversation *converation = [self.dataSource objectAtIndex:indexPath.row];
        [[EaseMob sharedInstance].chatManager removeConversationByChatter:converation.chatter deleteMessages:YES append2Chat:YES];
        [self.dataSource removeObjectAtIndex:indexPath.row];
        
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        //[self refreshDataSource];
    }
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_slimeView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_slimeView scrollViewDidEndDraging];
}

#pragma mark - slimeRefresh delegate
//刷新消息列表
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [self refreshDataSource];
    [_slimeView endRefresh];
}

#pragma mark - IChatMangerDelegate

-(void)didUnreadMessagesCountChanged
{
    [self refreshDataSource];
}

- (void)didUpdateGroupList:(NSArray *)allGroups error:(EMError *)error
{
    [self refreshDataSource];
}

#pragma mark - registerNotifications
-(void)registerNotifications{
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)dealloc{
    [self unregisterNotifications];
}

#pragma mark - public

-(void)refreshDataSource
{
    self.dataSource = [self loadDataSource];
    
    [_tableView reloadData];
    [self hideHud];
}

- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        _tableView.tableHeaderView = _networkStateView;
    }
    else{
        _tableView.tableHeaderView = nil;
    }
    
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == eEMConnectionDisconnected) {
        _tableView.tableHeaderView = _networkStateView;
    }
    else{
        _tableView.tableHeaderView = nil;
    }
}

- (void)willReceiveOfflineMessages{
    NSLog(NSLocalizedString(@"message.beginReceiveOffine", @"Begin to receive offline messages"));
}

- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages
{
    [self refreshDataSource];
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages{
    NSLog(NSLocalizedString(@"message.endReceiveOffine", @"End to receive offline messages"));
    [self refreshDataSource];
}

#pragma mark - ChatViewControllerDelegate

// 根据环信id得到要显示头像路径，如果返回nil，则显示默认头像
- (NSString *)avatarWithChatter:(NSString *)chatter{
    //    return @"http://img0.bdstatic.com/img/image/shouye/jianbihua0525.jpg";
    return nil;
}

// 根据环信id得到要显示用户名，如果返回nil，则默认显示环信id
- (NSString *)nickNameWithChatter:(NSString *)chatter{
    return chatter;
}

#pragma mark - 获取环信用户

-(void)getAllHuanXinUserInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"addressbook_galler.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        //NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"addressbook_galler"]) {
            
            NSDictionary *dataDic=[result objectForKey:@"data"];
            NSArray *listArray=[dataDic objectForKey:@"list"];
            NSLog(@"环信用户个数%lu",listArray.count);
            if (listArray.count>0) {
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                NSMutableDictionary *huanXinDic=[[NSMutableDictionary alloc]init];
                for (NSDictionary *dic in listArray) {
                    
                    TongXunLu *tongXunLu=[TongXunLu yy_modelWithDictionary:dic];
                    [huanXinDic setObject:tongXunLu.truename forKey:[NSString stringWithFormat:@"%@name",tongXunLu.huanxin_username]];
                    [huanXinDic setObject:tongXunLu.pic forKey:[NSString stringWithFormat:@"%@pic",tongXunLu.huanxin_username]];
                    [huanXinDic setObject:[NSString stringWithFormat:@"%d",tongXunLu.userid] forKey:[NSString stringWithFormat:@"%@userid",tongXunLu.huanxin_username]];
                }
                [userDefault setObject:huanXinDic forKey:@"huanXinInfo"];
                [userDefault synchronize];
                _huanXinDic=huanXinDic;
                [self.tableView reloadData];
            }
        }
        
    }failureAction:^{
        
    }];
}

#pragma mark - 获取通讯录

-(void)getTongXunLuInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"addressbook_v1.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        //NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"addressbook_v1"]) {
            
            NSDictionary *dataDic=[result objectForKey:@"data"];
            NSArray *listArray=[dataDic objectForKey:@"list"];
            
            if (listArray.count>0) {
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setObject:listArray forKey:@"tongXunLuArray"];
                [userDefault synchronize];
            }
            
        }
        
    }failureAction:^{
        
    }];
}

#pragma mark - 获取与我相关的群组

-(void)getMyGroupInfo{
    
    [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsListWithCompletion:^(NSArray *groups, EMError *error) {
        if (!error) {
            
            NSLog(@"与我相关的群组%@",[groups description]);
            if (groups.count<1) {
                [self removeGroupChatFromeChatList];
            }else{
                [self removeEmptyConversationsFromDB];
            }
        }
    } onQueue:nil];
    
}

-(void)removeGroupChatFromeChatList{
    
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (conversation.conversationType == eConversationTypeGroupChat) {
            
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:YES];
    }
    [self refreshDataSource];
}

@end
